package top.lingkang.finaloauth2.examplespringboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import top.lingkang.finaloauth2.client.http.ResourceServerHolder;
import top.lingkang.finaloauth2.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lingkang
 * Created by 2022/3/23
 */
@RestController
public class WebController {
    @Autowired
    private ResourceServerHolder resourceServerHolder;

    @GetMapping("")
    public Object index() {
        return new ModelAndView("index");
    }

    @GetMapping("/code")
    public Object code() {
        ModelAndView view = new ModelAndView("auth.html");
        return view;
    }

    @PostMapping("/code/confirm")
    public Object confirm(HttpServletResponse response) {
        String code = resourceServerHolder.generateAuthCode("1", "", "");
        try {
            response.sendRedirect("/code/auth-code-success?code=" + code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("/code/auth-code-success")
    public ModelAndView authSuccess(String code, HttpServletRequest request) {
        request.setAttribute("code", code);
        return new ModelAndView("auth-code-success.html");
    }

    @GetMapping("/code/token")
    public Object authCodeToken(String code) {
        return resourceServerHolder.authCodeGetToken(code);
    }


    @GetMapping("/password")
    public Object password() {
        return new ModelAndView("password");
    }

    @PostMapping("/password")
    public Object login(String username, String password) {
        if (StringUtils.isEmpty(username)) {
            return "username 不能为空！";
        }
        if (StringUtils.isEmpty(password)) {
            return "password 不能为空！";
        }
        try {
            return resourceServerHolder.login(username, password);
        } catch (Exception e) {
            e.printStackTrace();
            return "账号不存在或密码错误！";
        }
    }

    @PostMapping("/password/refreshToken")
    public Object refreshToken(String refreshToken) {
        if (StringUtils.isEmpty(refreshToken)) {
            return "refreshToken 不能为空！";
        }
        return resourceServerHolder.refreshToken(refreshToken);
    }

    @RequestMapping("/password/logout")
    public Object logout(String token) {
        if (StringUtils.isEmpty(token)) {
            return "refreshToken 不能为空！";
        }
        return resourceServerHolder.logout(token);
    }
}
